package com.android.ddfafu.activity;

import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import com.android.ddfafu.MapApplication;
import com.android.ddfafu.R;
import com.android.ddfafu.result.CameraResult;
import com.android.ddfafu.result.MyBundleData;
import com.android.ddfafu.utils.BitmapUtil;
import com.android.ddfafu.utils.CameraUtil;
import com.android.ddfafu.utils.Const;
import com.android.ddfafu.utils.UploadImageThead;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.navigation.NavigationView;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private UploadImageThead mUploadImageThread;
    private CameraResult result;
    private SharedPreferences sp_user;
    private SharedPreferences sp_img;



    private AppBarConfiguration mAppBarConfiguration;
    private NavController navController;
    private NavigationView navigationView;
    private MapApplication application;
    private String usernameSub;
    private volatile boolean flag = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener((v) -> {
            //点击拍照 2020年1月7日00:09:20
            CameraUtil cameraUtil = new CameraUtil(MainActivity.this, getApplication());
            result = cameraUtil.startCamera();
            startActivityForResult(result.getIntent(), Const.REQUEST_CAMERA);
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);

        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        Log.i("Activity", "onCreate");

        //初始化自定义本地存储的信息配置
        initSharedPreferences();
        updateHearderViewUI();

        ////小bug修复 解决每次都会加载上一个登录用户的图片
        //application = (MapApplication) getApplication();
        //List<Bitmap> bitmapList = application.getBitmapList();
        //bitmapList.clear();

        //不能这样做 会导致UI刷新不全 有几率造成APP闪退
      /*  String delete_img = getIntent().getStringExtra("delete_img");
        new Thread(()->{
            while (!flag){
            }
            if (delete_img != null && delete_img.equals("ok")) {
                runOnUiThread(()-> navController.navigate(R.id.nav_gallery));
            }
        }).start();*/
    }

    private void initSharedPreferences(){
        //初始化自定义本地存储的信息配置
        sp_img = this.getSharedPreferences("userImages", Context.MODE_PRIVATE);
        sp_user = this.getSharedPreferences("userData", Context.MODE_PRIVATE);
        usernameSub = sp_user.getString("USERNAME", "").replace("@", "").replace(".", "");
        if (sp_img.getStringSet(usernameSub, null) == null) {
            Set<String> pathSet = new HashSet<>();
            SharedPreferences.Editor edit = sp_img.edit();
            edit.putStringSet(usernameSub, pathSet);
            edit.apply();
            edit.commit();
        } else {
            System.out.println("已经创建好了");
        }

    }

    public void updateHearderViewUI() {
        Intent intent = getIntent();
        String username = intent.getStringExtra("username");
        String name = intent.getStringExtra("name");
        if (username != null || name != null) {
            View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
            TextView mName = headerLayout.findViewById(R.id.name);
            TextView mUsername = headerLayout.findViewById(R.id.username);
            mName.setText("Hello, " + name);
            mUsername.setText(username);
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.i("onCreateOptionsMenu","onCreateOptionsMenu");
        getMenuInflater().inflate(R.menu.main, menu);
        flag = true;
        return true;
    }



    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        Log.i("onOptionsItemSelected","onOptionsItemSelected");
        switch (item.getItemId()) {
            case R.id.action_settings:
                navController.navigate(R.id.nav_share);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);

    }

    @Override
    public boolean onSupportNavigateUp() {
        Log.i("onSupportNavigateUp","onSupportNavigateUp");
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Const.REQUEST_CAMERA:
                if (resultCode != RESULT_OK) {
                    return;
                }
                try {
                    //获取缩略图
                    //Bitmap thumbnail = data.getParcelableExtra("data");
                    //Uri uri = data.getData();
                    Uri uri = result.getUri();
                    if (uri == null) {
                        System.out.println("Uri 为空");
                        return;
                    }
                    System.out.println(" uri path " + uri.getPath());
                    System.out.println(" uri fromfile后的URLPATH" + Uri.fromFile(new File(uri.getPath())).getPath());


                    if (Build.VERSION.SDK_INT < 29) {
                        String dir = Environment.getExternalStorageDirectory() + "/images/"
                                + sp_user.getString("USERNAME","").replace("@","").replace(".","") + "/";
                        String name = result.getImage().getName();

                        System.out.println(dir);
                        //把拍完的照片路径信息保存至本地
                        Set<String> image_path = sp_img.getStringSet(usernameSub, null);
                        if (image_path != null) {
                            Set<String> pathSet = new HashSet<>(image_path);
                            pathSet.add(dir + name);
                            SharedPreferences.Editor edit = sp_img.edit();
                            edit.putStringSet(usernameSub, pathSet);
                            edit.apply();
                            edit.commit();
                        }
                    }

                    //兼容Android 10.0
                    if (Build.VERSION.SDK_INT == 29){
                        String dir = this.getExternalFilesDir(null) + "/images/"
                                + sp_user.getString("USERNAME","").replace("@","").replace(".","") + "/";
                        System.out.println(dir);
                        String name = result.getImage().getName();
                        Set<String> image_path = sp_img.getStringSet(usernameSub, null);
                        if (image_path != null) {
                            Set<String> pathSet = new HashSet<>(image_path);
                            pathSet.add(dir + name);
                            SharedPreferences.Editor edit = sp_img.edit();
                            edit.putStringSet(usernameSub, pathSet);
                            edit.apply();
                            edit.commit();
                        }
                    }

                    Bitmap bitmap = BitmapUtil.getBitmapFromUri(this,uri);
                    // date 2020年1月6日14:14:51
                    //覆盖在地图上显示缩略图
                    application = (MapApplication) getApplication();
                    LatLng point = application.getLatLng();
                    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                    OverlayOptions option = new MarkerOptions()
                            .position(point) //必传参数
                            .icon(bitmapDescriptor)
                            .scaleX(0.05f)
                            .scaleY(0.05f)
                            .perspective(true); //必传参数

                    //将option对象 通过自定义Bundle存进进Application中 让整个应用共享
                    Bundle bundle = new Bundle();
                    MyBundleData myBundleData = new MyBundleData(option);
                    bundle.putSerializable("MARKER", myBundleData);
                    application.addBundle(bundle);

                    Thread.sleep(300);
                    navController.navigate(R.id.nav_home);
                    Log.i("设置图片", "设置成功");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                //上传图片到服务器
                if (result.getImage() != null && result.getImage().exists()) {
                    //String token = "";

                    //运行中有效
                    //MapApplication application = (MapApplication) getApplication();
                    //String username = application.getApplicationUsername();
                    //String token1 = application.getApplicationToken();
                    //System.out.println(username+"--------------"+token1);

                    //一直有效
                    SharedPreferences sp = this.getSharedPreferences("userData", Context.MODE_PRIVATE);
                    String username = sp.getString("USERNAME", "");
                    String token = sp.getString("TOKEN", "");

                    mUploadImageThread = new UploadImageThead(result.getImage(), token, username);
                    mUploadImageThread.setUploadImageListener(new UploadImageThead.UploadImageListener() {
                        @Override
                        public void uploadImageFail() {
                            Log.e("ERROR", "上传图片失败");
                        }

                        @Override
                        public void uploadImageSuccess() {
                            Log.i("SUCCESS", "上传图片成功");
                        }
                    });
                    mUploadImageThread.start();
                }
                break;
            default:
                break;
        }
    }

}
